package cn.wonhigh.o2o.openfire.plugins.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTP请求工具类.
 * 
 * @author zhang.dk
 * @date 2014-6-7 上午11:02:17
 * @version 0.1.0
 * @copyright yougou.com
 */
public final class HttpUtil {
	private static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);

	private HttpUtil() {
	}

	public static String httpPost(String requestURL, Map<String, String> params) {
		try {
			LOG.info("POST 请求路径：url={}，content={}", requestURL, params);
			HttpURLConnection connection = buildConnection(requestURL);
			configConnection(connection, RequestMethod.POST);
			connection.connect();
			writeContent(params, connection);
			return readResponseAndCloseResource(connection);
		} catch (IOException e) {
			LOG.error("发送HTTP POST请求时出错", e);
		}
		return null;
	}

	private static HttpURLConnection buildConnection(String requestURL)
			throws MalformedURLException, IOException {
		URL url = new URL(requestURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		return connection;
	}

	private static void configConnection(HttpURLConnection connection,
			RequestMethod method) throws ProtocolException {
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod(method.toString());
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
	}

	private static String readResponseAndCloseResource(
			HttpURLConnection connection) throws IOException {
		BufferedReader reader = null;
		StringBuilder buff = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				buff.append(line);
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
			connection.disconnect();
		}
		return buff.toString();
	}

	private static void writeContent(Map<String, String> params,
			HttpURLConnection connection) throws IOException,
			UnsupportedEncodingException {
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		StringBuilder buff = new StringBuilder();
		Set<String> keys = params.keySet();
		boolean after = false;
		for (String key : keys) {
			if (after) {
				buff.append("&");
			} else {
				after = true;
			}
			buff.append(key).append("=")
					.append(URLEncoder.encode(params.get(key), "UTF-8"));
		}
		LOG.info("POST请求的主体内容：{}", buff.toString());
		out.writeBytes(buff.toString());
		out.flush();
		out.close();
	}

	public static enum RequestMethod {
		GET, POST;
	}
}